package njitzx;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

public class HumanFactory {
    private static Properties properties = new Properties();

    static {
        try (InputStream input = HumanFactory.class.getClassLoader().getResourceAsStream("human.properties")) {
            if (input == null) {
                throw new RuntimeException("无法找到 human.properties 配置文件");
            }
            properties.load(input);
        } catch (IOException e) {
            throw new RuntimeException("加载配置文件失败", e);
        }
    }

    public static Human createHuman() {
        String className = properties.getProperty("human.class");
        try {
            Class<?> clazz = Class.forName(className);  //加载类名
            Object obj = clazz.getDeclaredConstructor().newInstance();

            // 设置属性
            for (String key : properties.stringPropertyNames()) {
                if (key.startsWith("human.") && !key.equals("human.class")) {
                    String propertyName = key.substring("human.".length());
                    String propertyValue = properties.getProperty(key);

                    // 构造 setter 方法名
                    String methodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);

                    // 获取对应的 setter 方法
                    for (Method method : clazz.getMethods()) {
                        if (method.getName().equals(methodName)) {
                            Class<?> paramType = method.getParameterTypes()[0];
                            Object value = convert(propertyValue, paramType);
                            method.invoke(obj, value);
                            break;
                        }
                    }
                }
            }

            return (Human) obj;
        } catch (Exception e) {
            throw new RuntimeException("创建 Human 对象失败", e);
        }
    }

    // 辅助方法：将字符串转换为指定类型
    private static Object convert(String value, Class<?> targetType) {
        if (targetType == String.class) {
            return value;
        } else if (targetType == int.class || targetType == Integer.class) {
            return Integer.parseInt(value);
        }
        // 可以根据需要扩展更多类型
        throw new IllegalArgumentException("Unsupported property type: " + targetType);
    }
}
